package com.canbot.u05.activity.customvoice;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.adapter.CustomDialogListAdapter;
import com.canbot.u05.activity.customvoice.bean.AnswerBean;
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelData;
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas;
import com.canbot.u05.activity.customvoice.bean.QuestionBean;
import com.canbot.u05.activity.customvoice.tool.CommomDialog;
import com.canbot.u05.activity.customvoice.tool.ExportExcelUtils;
import com.canbot.u05.bean.CustomDialogue;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;


/**
 * 自定义对话列表界面
 *
 * @author Liu.Heng
 * @date 2018/5/24
 */

public class CustomDialogListActivity extends BaseActivityNoTitle implements CustomDialogListAdapter.Callback {

        private static final String TAG = "CustomDialogListActivity";

        private RecyclerView mListView;

        private RelativeLayout mRelativeLayout;

        private List<QuestionBean> mListDatas;

        private CustomDialogListAdapter mMyAdapter;

        private List<QuestionBean> mDelDatas;

        private List<String> questions = new ArrayList<>();

        private Dialog dialogLoading;

        private Button chooseall_Btn;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_custom_dialog_list);
                mListDatas = new ArrayList<>();
                mDelDatas = new ArrayList<>();
                initView();
        }

        private void initView() {
                chooseall_Btn = findViewById(R.id.chooseall_btn);
                mListView = (RecyclerView) findViewById(R.id.my_listView);
                mListView.setLayoutManager(new LinearLayoutManager(this));
                mRelativeLayout = (RelativeLayout) findViewById(R.id.remind_relativeLayout);
                mMyAdapter = new CustomDialogListAdapter(this, mListDatas, this);
                mListView.setAdapter(mMyAdapter);
        }

        @Override
        public void clickEvent(View v, int i) {

                switch (i) {
                        //勾选按钮添加
                        case 1:
                                mDelDatas.add(mListDatas.get((Integer) v.getTag()));
                                break;
                        //勾选按钮取消
                        case 2:
                                mDelDatas.remove(mListDatas.get((Integer) v.getTag()));
                                break;
                        //修改对话
                        case 3:
                                getAnswerData(mListDatas.get((Integer) v.getTag()).getQuestion(), CustomQuestionActivity.class);
                                break;
                        //修改图片
                        case 4:
                                getAnswerData(mListDatas.get((Integer) v.getTag()).getQuestion(), CustomImageActivity.class);
                                break;
                        //修改动作
                        case 5:
                                getAnswerData(mListDatas.get((Integer) v.getTag()).getQuestion(), CustomActionSetActivity.class);
                                break;
                        default:
                                break;
                }
        }


        private void getAnswerData(final String question, final Class cls) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomDialogListActivity.this, getString(R.string.loading));
                dialogLoading.show();
                final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom";
                final HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("type", "7");
                hashMap.put("question", question);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @SuppressLint("LongLogTag")
                        @Override
                        public void onSuccess(String result) {
                                if (dialogLoading != null) {
                                        dialogLoading.dismiss();
                                }
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }
                                else {
                                        msg = "加载成功";
                                        final AnswerBean answerBean = JSON.parseObject(strMsgBean.getResult().toString(), AnswerBean.class);
                                        if (answerBean != null) {
                                                final Intent intent = new Intent(CustomDialogListActivity.this, cls);
                                                intent.putExtra("type", 1);
                                                intent.putExtra("question_Str", question);
                                                intent.putExtra("answer", JSON.toJSONString(answerBean));
                                                startActivity(intent);
                                        }
                                        Log.e(TAG, answerBean + "");
                                }
                                Log.e(TAG, msg);
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (dialogLoading != null) {
                                                        dialogLoading.dismiss();
                                                }
                                                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void getDatas() {
                mListDatas.clear();
                mDelDatas.clear();
                questions.clear();

                final List<CustomDialogue> questionList = new ArrayList<>();
                for (int i = 0; i < ((MainApplication) getApplication()).mCustomDialogues.size(); i++) {
                        questionList.add(((MainApplication) getApplication()).mCustomDialogues.get(i));
                }
                dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomDialogListActivity.this, getString(R.string.loading));
                dialogLoading.show();
                final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom";
                final HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("type", "5");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @SuppressLint("LongLogTag")
                        @Override
                        public void onSuccess(String result) {
                                if (dialogLoading != null) {
                                        dialogLoading.dismiss();
                                }
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                final String msg;

                                if (strMsgBean.getRc() != 0) {
                                        msg = strMsgBean.getMsg();
                                }
                                else {
                                        msg = "加载成功";
                                }

                                final List<QuestionBean> questionBeanList = JSON.parseArray(strMsgBean.getResult().toString(), QuestionBean.class);
                                for (int i = 0; i < questionBeanList.size(); i++) {
                                        Logger.e(TAG, "---------->" + questionBeanList.get(i) + "");
                                        if (questionBeanList.get(i).getType() == 1) {
                                                mListDatas.add(questionBeanList.get(i));
                                                questions.add(questionBeanList.get(i).getQuestion());
                                        }
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (mListDatas.size() > 0) {
                                                        Collections.sort(mListDatas, new Comparator<QuestionBean>() {
                                                                @Override
                                                                public int compare(QuestionBean questionBean, QuestionBean t1) {
                                                                        return t1.getCmd_id().compareTo(questionBean.getCmd_id());
                                                                }
                                                        });
                                                        mRelativeLayout.setVisibility(View.GONE);
                                                        mMyAdapter.notify(mListDatas);
                                                }
                                                else {
                                                        mRelativeLayout.setVisibility(View.VISIBLE);
                                                        SPUtils.saveBoolean(CustomDialogListActivity.this, "isHaveData", false);
                                                }
                                                ToastTools.newInstance(getApplicationContext()).showText(msg);
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (dialogLoading != null) {
                                                        dialogLoading.dismiss();
                                                }
                                                ToastTools.newInstance(getApplicationContext()).showText(CustomDialogListActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        @Override
        protected void onResume() {
                super.onResume();
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzdh_001.wav");
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "30");
                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14003");
                getDatas();
        }

        /**
         * 返回
         */
        public void back(View view) {
                finish();
        }

        /**
         * 批量导入
         */
        public void importData(View view) {

                startActivity(new Intent(CustomDialogListActivity.this, CustomDialogActivity.class).putExtra("data", JSON.toJSONString(questions)).putExtra("type", 0));
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_pldr_001.wav");
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "18");
                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14008");
        }

        /**
         * 数据导出
         */
        public void exportData(View view) {
                getAllQsAndAs();
        }

        /**
         * 新建数据
         */
        public void newDialogue(View view) {

                startActivity(new Intent(CustomDialogListActivity.this, CustomQuestionActivity.class).putExtra("data", JSON.toJSONString(mListDatas)));
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzwt_001.wav");
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "12");
                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14004");
        }

        /**
         * 选中全部数据
         */
        public void chooseAll(View view) {
                if (mDelDatas != null && mDelDatas.size() == mListDatas.size()) {
                        mDelDatas.clear();
                        mMyAdapter.notifyChooseAll(false);
                        chooseall_Btn.setText(CustomDialogListActivity.this.getString(R.string.dialog_choose_all));
                        return;
                }

                if (mDelDatas != null) {
                        mDelDatas.clear();
                        mDelDatas.addAll(mListDatas);
                        mMyAdapter.notifyChooseAll(true);
                        chooseall_Btn.setText(CustomDialogListActivity.this.getString(R.string.dialog_choose_all_false));
                }
        }

        /**
         * 删除数据
         */
        public void deleteData(View view) {

                if (mDelDatas.size() == 0) {
                        ToastTools.newInstance(getApplicationContext()).showText("请先勾选出您想要删除的对话");
                        return;
                }

                new CommomDialog(this, R.style.dialog, "是否删除这" + mDelDatas.size() + "条对话", false, false, false, "确认", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                        dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomDialogListActivity.this, "正在删除中...");
                                        dialogLoading.show();
                                        final List<String> questionNames = new ArrayList<>();
                                        for (int i = 0; i < mDelDatas.size(); i++) {
                                                questionNames.add(mDelDatas.get(i).getQuestion());
                                        }
                                        final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom";
                                        final HashMap<String, String> hashMap = new HashMap<>();
                                        hashMap.put("type", "1");
                                        hashMap.put("questions", JSON.toJSONString(questionNames));
                                        OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                                                @SuppressLint("LongLogTag")
                                                @Override
                                                public void onSuccess(String result) {
                                                        final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                                        final String msg;

                                                        if (strMsgBean.getRc() != 0) {
                                                                msg = strMsgBean.getMsg();
                                                        }
                                                        else {
                                                                msg = CustomDialogListActivity.this.getString(R.string.deleted_successfully);
                                                        }
                                                        runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                        if (strMsgBean.getRc() == 0) {
                                                                                if (dialogLoading != null) {
                                                                                        dialogLoading.dismiss();
                                                                                }
                                                                                ToastTools.newInstance(getApplicationContext()).showText(msg);

                                                                                getDatas();
                                                                        }
                                                                }
                                                        });
                                                }

                                                @Override
                                                public void onFailure() {
                                                        runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                        if (dialogLoading != null) {
                                                                                dialogLoading.dismiss();
                                                                        }
                                                                        ToastTools.newInstance(getApplicationContext()).showText(CustomDialogListActivity.this.getString(R.string.delete_failed));
                                                                }
                                                        });
                                                }
                                        });
                                        dialog.dismiss();
                                }
                        }
                }).setTitle("提示").show();
        }

        /**
         * 导出数据为 Excel
         */
        private void getAllQsAndAs() {
                if (mListDatas.size() == 0 || mListDatas == null) {
                        ToastTools.newInstance(getApplicationContext()).showText("自定义对话数据为空");
                        return;
                }

                dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomDialogListActivity.this, getString(R.string.loading));
                dialogLoading.show();
                final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom";
                final HashMap<String, String> hashMap = new HashMap<>(1);
                hashMap.put("type", "8");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @SuppressLint("LongLogTag")
                        @Override
                        public void onSuccess(String result) {
                                exportExcelData(result);
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (dialogLoading != null) {
                                                        dialogLoading.dismiss();
                                                }
                                                ToastTools.newInstance(getApplicationContext()).showText(CustomDialogListActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        private void exportExcelData(String string) {
                Logger.e("数据导出", string);
                final JsonResponse strMsgBean = JSON.parseObject(string, JsonResponse.class);
                final String msg;
                if (strMsgBean.getRc() != 0) {
                        msg = strMsgBean.getMsg();
                }
                else {
                        msg = "导出数据成功!";
                }
                final CustomDialogExcelDatas customDialogExcelData = JSON.parseObject(strMsgBean.getResult().toString(), CustomDialogExcelDatas.class);
                final List<QuestionBean> questionBeans = customDialogExcelData.getListQsBean();
                Collections.sort(questionBeans, new Comparator<QuestionBean>() {
                        @Override
                        public int compare(QuestionBean t1, QuestionBean t2) {
                                return t1.getCmd_id().compareTo(t2.getCmd_id());
                        }
                });
                final List<QuestionBean> questionBeanList = new ArrayList<>();
                for (int i = 0; i < questionBeans.size(); i++) {
                        if (questionBeans.get(i).getType() == 1) {
                                questionBeanList.add(questionBeans.get(i));
                        }
                }
                final List<AnswerBean> answerBeanList = customDialogExcelData.getListAsBean();
                final List<CustomDialogExcelData> customDialogExcelDatas = new ArrayList<>();
                Collections.sort(answerBeanList, new Comparator<AnswerBean>() {
                        @Override
                        public int compare(AnswerBean t1, AnswerBean t2) {
                                return t1.getCmd_id().compareTo(t2.getCmd_id());
                        }
                });
                runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                                final List<QuestionBean> myQs = new ArrayList<>();
                                final List<AnswerBean> myAs = new ArrayList<>();
                                Logger.e("数据导出", questionBeanList.size() + "");
                                Logger.e("数据导出", answerBeanList.size() + "");
                                for (int i = 0; i < questionBeanList.size(); i++) {
                                        QuestionBean questionBean = questionBeanList.get(i);
                                        myQs.add(questionBean);
                                        if (i < questionBeanList.size() - 1) {
                                                if (questionBean.getCmd_id().equals(questionBeanList.get(i + 1).getCmd_id())) {
                                                        continue;
                                                }
                                        }
                                        for (int j = 0; j < answerBeanList.size(); j++) {
                                                final AnswerBean answerBean = answerBeanList.get(j);
                                                if (questionBean.getCmd_id().equals(answerBeanList.get(j).getCmd_id())) {
                                                        myAs.add(answerBean);
                                                        continue;
                                                }
                                        }
                                        if (myQs.size() >= myAs.size()) {
                                                for (int k = 0; k < myQs.size(); k++) {
                                                        final CustomDialogExcelData customDialogExcelData = new CustomDialogExcelData();
                                                        customDialogExcelData.setQustion_str(myQs.get(k).getQuestion());
                                                        customDialogExcelData.setTts_text(myAs.size() > k ? (myAs.get(k).getType() == 1 ? myAs.get(k).getTtstext() : myAs.get(k).getSoundpath()) : "");
                                                        customDialogExcelData.setImage_path(myAs.size() > k ? (myAs.get(k).getImgpath().isEmpty() ? "" : myAs.get(k).getImgpath()) : "");
                                                        customDialogExcelDatas.add(customDialogExcelData);
                                                }
                                        }
                                        else {
                                                for (int k = 0; k < myAs.size(); k++) {
                                                        final CustomDialogExcelData customDialogExcelData = new CustomDialogExcelData();
                                                        customDialogExcelData.setQustion_str(myQs.size() > k ? myQs.get(k).getQuestion() : "");
                                                        customDialogExcelData.setTts_text(myAs.get(k).getType() == 0 ? myAs.get(k).getTtstext() : myAs.get(k).getSoundpath());
                                                        customDialogExcelData.setImage_path(myAs.get(k).getImgpath().isEmpty() ? "" : myAs.get(k).getImgpath());
                                                        customDialogExcelDatas.add(customDialogExcelData);
                                                }
                                        }
                                        myQs.clear();
                                        myAs.clear();
                                }
                                if (customDialogExcelDatas.size() > 0) {
                                        Logger.e("数据导出", customDialogExcelDatas.size() + "");
                                        Logger.e("数据导出", customDialogExcelDatas.get(0).toString());
                                        String filePath = Environment.getExternalStorageDirectory().toString() + File.separator;
                                        File file = new File(filePath);
                                        if (!file.exists()) {
                                                file.mkdirs();
                                        }
                                        String excelFileName = "/自定义对话Excel.xls";
                                        String[] title = {"问题", "答案", "图片"};
                                        filePath = filePath + excelFileName;
                                        ExportExcelUtils.initExcel(filePath, title);
                                        ExportExcelUtils.writeObjListToExcel(customDialogExcelDatas, filePath);
                                        if (dialogLoading != null) {
                                                dialogLoading.dismiss();
                                        }
                                        new CommomDialog(CustomDialogListActivity.this, R.style.dialog, "请用电脑连接平板,SD卡目录下'自定义对话Excel.xls'为导出文件", true, "知道了", new CommomDialog.OnCloseListener() {
                                                @Override
                                                public void onClick(Dialog dialog, boolean confirm) {
                                                        dialog.dismiss();
                                                }
                                        }).setTitle("导出成功!").show();
                                }
                                else {
                                        ToastTools.newInstance(getApplicationContext()).showText("数据为空!");
                                }
                        }
                });
        }


        @Override
        protected void onDestroy() {
                // TODO Auto-generated method stub
                if (dialogLoading != null && dialogLoading.isShowing()) {
                        dialogLoading.dismiss();
                }
                super.onDestroy();
        }


}
